<template>
  <view class="uni-container">
    <uni-forms ref="form" :value="formData" validateTrigger="bind">
	  <uni-forms-item name="comment" label="留言内容" required>
		<textarea @input="binddata('comment', $event.detail.value)" class="uni-textarea-border" v-model="formData.comment" trim="both" />
	  </uni-forms-item>
	  <uni-forms-item label="图片列表" name="bbs_img">
		<input @input="binddata('bbs_img', $event.detail.value)" v-model="formData.bbs_img" trim="both" 
		placeholder="暂无图片"/>
	  </uni-forms-item>
      <uni-forms-item name="bbs_name" label="联系人" >
        <input @input="binddata('bbs_name', $event.detail.value)" class="uni-input-border" v-model="formData.bbs_name" trim="both"/>
      </uni-forms-item>
      <uni-forms-item name="bbs_phone" label="联系电话" >
        <input @input="binddata('bbs_phone', $event.detail.value)" class="uni-input-border" v-model="formData.bbs_phone" trim="both" />
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">{{$t('common.button.submit')}}</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
            <button class="uni-button" style="width: 100px;">{{$t('common.button.back')}}</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>
<script>
  import { validator } from '@/js_sdk/validator/uni-id-bbs.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'uni-id-bbs';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  export default {
    data() {
      let formData = {
        "comment": "",
        "bbs_img": "",
        "bbs_name": "",
		"bbs_phone":"",
		"create_date":""
      }
      return {
        formData,
        formOptions: {},
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 触发表单提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          this.submitForm(res)
        }).catch(() => {
          uni.hideLoading()
        })
      },

      submitForm(value) {
        // 使用 clientDB 提交数据
        db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '添加成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
<style lang="scss">
</style>